import { useState, useEffect } from "react";
import { Common } from 'UtilsCommon';

const _PageConfigs = {};

export default (name, id, dispatchAction) => {
  const [pageConfig, setPageConfig] = useState(_PageConfigs[name + id]);

  useEffect(() => {
    if (!pageConfig) {
      const pageId = id || Common.getQueryString().id;
      const isPreview = id || name === "preview";
      const pathQuery = isPreview ? `/getconfig?id=${pageId}` : `/${name.replace("_", "/")}.json`;
      dispatchAction("WebService", "getConfig", { pathQuery }).then(res => {
        if (id) res.isDiv = false;
        _PageConfigs[name + id] = res;
        setPageConfig(res);
      });
    }
  }, [pageConfig, name, dispatchAction]);

  return pageConfig;
};
